<?php

namespace App\Service\OpenShop\SiteLocation;

use App\Enums\OpenShop\FeishuMini\SandTableEnum;
use App\Enums\OpenShop\Merchant\IntendedSiteLocationEnum;
use App\Events\OpenShop\IntendedSiteSelection\InsertEvent;
use App\Enums\Common\AreaEnum;
use App\Enums\OpenShop\FeishuMini\ProgrammingEnum;
use App\Enums\OpenShop\InvestmentPromotion\SiteLocationEnum;
use App\Exceptions\Custom\ResponseHttpException;
use App\Http\Middleware\OpenShop\WangGuiCityByPower;
use App\Http\Resources\OpenShop\SiteLocation\IntendedSiteSelectionListResource;
use App\Library\Rms\RmsUserApi;
use App\Models\Amap\AmapRegionBoundaryModel;
use App\Models\Common\CityResidencePriceModel;
use App\Models\Common\MapNationalBrandShopModel;
use App\Models\Common\MapNationalCommunityModel;
use App\Models\Common\MapNationalIndustrialParkModel;
use App\Models\Common\MapNationalStreetModel;
use App\Models\Common\MapNationalUniversitiesModel;
use App\Models\Common\MapTownshipPlanAreaModel;
use App\Models\Common\OperateLogModel;
use App\Models\Common\ResourcesModel;
use App\Models\Guanyuan\GuanyuanSyncShopListModel;
use App\Models\OpenShop\Common\SiteLocationMallModel;
use App\Models\OpenShop\InvestmentPromotion\OpenShopMainProcessModel;
use App\Models\OpenShop\InvestmentPromotion\OpenShopOrganizationManageModel;
use App\Models\OpenShop\InvestmentPromotion\OpenShopOrganizationManageUserModel;
use App\Models\OpenShop\InvestmentPromotion\OpenShopOrganizationRegionMappingModel;
use App\Models\OpenShop\InvestmentPromotion\OpenShopUserBaseInfoModel;
use App\Models\OpenShop\InvestmentPromotion\OpenShopUserIdentityCardModel;
use App\Models\OpenShop\SiteLocation\IntendedSiteSelectionModel;
use App\Models\OpenShop\SiteLocation\OpenShopSiteLocationModel;
use App\Models\Shop\ShopModel;
use App\Models\Wanggui\WangguiCollectionDotModel;
use App\Models\Wanggui\WangguiSearchDotModel;
use App\Remote\Rms\RmsAreaRemote;
use App\Remote\Rms\RmsUserRemote;
use App\Service\Common\AreaService;
use App\Service\Common\FileService;
use App\Service\OpenShop\Feishu\BaseService;
use App\Service\OpenShop\User\RmsUserService;
use App\Service\OpenShop\Wap\SignOrderService;
use App\Support\FeishuMsgSupport;
use Ballen\Distical\Entities\LatLong;
use Carbon\Carbon;
use GuzzleHttp\Exception\GuzzleException;
use Illuminate\Support\Facades\Http;
use Ballen\Distical\Calculator as DistanceCalculator;
use App\Service\Rms\ShopService;
use Illuminate\Support\Facades\Redis;
use Kuafu\File\FileUtil;
use League\Geotools\Coordinate\Coordinate;
use League\Geotools\Polygon\Polygon;
use OSS\Core\OssException;
use Psr\Container\ContainerExceptionInterface;
use Psr\Container\NotFoundExceptionInterface;

class IntendedSiteSelectionService extends \App\Service\BaseService
{
    /**
     * 意向选址列表
     *
     * @param object $params
     * @param int $shopId
     * @param int $uid
     * @return array
     */
    public static function list(object $params, int $shopId, int $uid): array
    {
        $paginate = IntendedSiteSelectionModel::query()
            ->where("shopId", $shopId)
            ->where("createdByUid", $uid)
            ->orderBy("id", "desc")
            ->paginate(
                $params->pageSize, ['*'], 'pageNum', $params->pageNum,
            );

        return [
            "list"     => IntendedSiteSelectionListResource::collection($paginate->items()),
            "count"    => $paginate->total(),
            "pageNum"  => $params->pageNum,
            "pageSize" => $params->pageSize
        ];
    }

    /**
     * 意向址删除
     *
     * @param object $params
     * @param int $uid
     */
    public static function del(object $params, int $uid)
    {
        IntendedSiteSelectionModel::query()->where("id", $params->id)->update([
            "isDeleted"    => 1,
            "updatedByUid" => $uid,
            "updatedAt"    => time()
        ]);
    }

    /**
     * 意向址添加
     *
     * @param object $params
     * @param int $shopId
     * @param int $uid
     * @throws OssException
     * @throws ContainerExceptionInterface
     * @throws NotFoundExceptionInterface
     */
    public static function insert(object $params, int $shopId, int $uid)
    {
        $existsCount = IntendedSiteSelectionModel::query()
            ->where("createdByUid", $uid)
            ->where("shopId", $shopId)
            ->count();
        if ($existsCount >= 20) {
            throw new ResponseHttpException(400, null, "当前门店用户仅支持添加20个意向选址");
        }

        $exist = IntendedSiteSelectionModel::query()
            ->where("createdByUid", $uid)
            ->where("shopId", $shopId)
            ->where("wgNumber", $params->wgNumber)
            ->where("type", $params->type)
            ->exists();

        if ($exist) {
            self::throwErr('已添加该意向点位');
        }

        // 根据wgNumber和type获得添加参数
        $data = self::getDotDetailByTypeAndWgNumber($params->type, $params->wgNumber);

        $siteSelectionImg = self::getAmapImage($data['lat'], $data['lng']);

        $id = IntendedSiteSelectionModel::query()->insertGetId(
            [
                "poiName"          => $data['name'],
                "poiAddress"       => $data['address'],
                "provinceCode"     => $data['provinceCode'],
                "cityCode"         => $data['cityCode'],
                "districtCode"     => $data['districtCode'],
                "addressPrefix"    => $data['province'] . '-' . $data['city'] . '-' . $data['district'],
                "longitude"        => $data['lng'],
                "latitude"         => $data['lat'],
                "shopId"           => $shopId,
                "type"             => $params->type,
                "wgNumber"         => $params->wgNumber,
                "createdByUid"     => $uid,
                "updatedByUid"     => $uid,
                "createdAt"        => time(),
                "updatedAt"        => time(),
                "siteSelectionImg" => FileService::transferred(
                    $siteSelectionImg,
                    md5($siteSelectionImg) . ".png",
                    "intendedSiteSelection",
                )
            ],
        );
        // todo 意向址添加完成事件触发
        event(new InsertEvent($id));
    }

    /**
     * 详情
     * @param int $id
     * @return array
     * @throws GuzzleException
     */
    public static function detail(int $id)
    {
        $intendedSiteSelectionModel = IntendedSiteSelectionModel::query()
            ->where('id', $id)
            ->first();

        if (null == $intendedSiteSelectionModel) {
            self::throwErr('意向址不存在', 404);
        }

        $dotInfo = self::dotInfoByLatAndLng($intendedSiteSelectionModel->longitude, $intendedSiteSelectionModel->latitude);

        return [
            'id'               => $intendedSiteSelectionModel->id,
            'poiName'          => $intendedSiteSelectionModel->poiName,
            'addressPrefix'    => $intendedSiteSelectionModel->addressPrefix,
            'poiAddress'       => $intendedSiteSelectionModel->poiAddress,
            'longitude'        => $intendedSiteSelectionModel->longitude,
            'latitude'         => $intendedSiteSelectionModel->latitude,
            'siteSelectionImg' => $intendedSiteSelectionModel->siteSelectionImg,
            'area'             => $dotInfo['area'] ?? [],
            'grade'            => $dotInfo['grade'] ?? '',
            'gradeText'        => $dotInfo['gradeText'] ?? '',
            'name'             => $dotInfo['name'] ?? '',
            'code'             => $dotInfo['code'] ?? '',
            'address'          => $dotInfo['address'] ?? '',
            'distance'         => $dotInfo['distance'] ?? '',
        ];
    }

    public static function verifySiteSelection()
    {

    }


    /**
     * 根据经纬度获得点位信息
     * @param $lng
     * @param $lat
     * @return array
     * @throws GuzzleException
     */
    public static function dotInfoByLatAndLng($lng, $lat): array
    {
        if (!$lng || !$lat) {
            return [];
        }

        $key     = WangGuiCityByPower::getRandomAmapKey();
        $areaRes = Http::withHeaders(['Content-Type' => 'application/json; charset=utf-8'])
            ->get(vsprintf(config('area.getReginDetailByLatLng'), [$lng, $lat, $key]))
            ->json();

        // $areaRes = Http::withHeaders(['Content-Type' => 'application/json; charset=utf-8'])
        //     ->get(sprintf(config('area.getAreaUrl'), $lat, $lng))
        //     ->json();
        if (($areaRes['status'] ?? -1) != 1) {
            return [
                'area'  => [],
                'grade' => (string)SiteLocationEnum::CITY_TYPE_LEVEL_5
            ];
        }

        $district = isset($areaRes['regeocode']['addressComponent']['district']) ? (is_array($areaRes['regeocode']['addressComponent']['district']) ? '' : $areaRes['regeocode']['addressComponent']['district']) : '';
        $city     = isset($areaRes['regeocode']['addressComponent']['city']) ? (is_array($areaRes['regeocode']['addressComponent']['city']) ? '' : $areaRes['regeocode']['addressComponent']['city']) : '';
        $province = isset($areaRes['regeocode']['addressComponent']['province']) ? (is_array($areaRes['regeocode']['addressComponent']['province']) ? '' : $areaRes['regeocode']['addressComponent']['province']) : '';
        $town     = isset($areaRes['regeocode']['addressComponent']['township']) ? (is_array($areaRes['regeocode']['addressComponent']['township']) ? '' : $areaRes['regeocode']['addressComponent']['township']) : '';

        if (!mb_strlen($city)) {
            $city     = $province;
        }
        if (!mb_strlen($district)) {
            if (!mb_strlen($city)) {
                $city     = $province;
                $district = $town;
            } else {
                $district = $city;
            }
        }

        $area = $province . '-' . $city . '-' . $district;

        $data = RmsUserService::getAreaCodeByArea($area);

        if (empty($data)) {
            return [];
        }
        $grade = SiteLocationEnum::CITY_TYPE_LEVEL_5;
        $res   = true;
        foreach ($data as $datum) {
            if ($datum['level'] == AreaEnum::LEVEL_PROVINCE) {
                //从RMS拿数据如果区域code为0 不自动匹配省市区  控制一级
                if ($datum['code'] == 0) {
                    $res = false;
                    break;
                }
                $province = [
                    'code' => $datum['code'],
                    'text' => $province,
                ];
            }
            if ($datum['level'] == AreaEnum::LEVEL_CITY) {
                $city  = [
                    'code' => $datum['code'],
                    'text' => $city,
                ];
                $grade = RmsAreaRemote::getCityGrade($datum['code']) ?: SiteLocationEnum::CITY_TYPE_LEVEL_5;
            }
            if ($datum['level'] == AreaEnum::LEVEL_DISTRICT) {
                $district = [
                    'code' => $datum['code'],
                    'text' => $district,
                ];
            }
        }

        $nearby             = GuanyuanDataService::closestShop($lat, $lng, '', false);
        $nearby['distance'] = (int)($nearby['distance'] * 1000);

        if (!isset($grade['cityInfo']['grade']) || !$grade['cityInfo']['grade']) {
            $grade = (string)SiteLocationEnum::CITY_TYPE_LEVEL_5;
        } else {
            $grade = (string)$grade['cityInfo']['grade'];
        }
        return array_merge([
            'area'      => $res ? [$province ?? 0, $city ?? 0, $district ?? 0] : [],
            'grade'     => $grade,
            'gradeText' => SiteLocationEnum::CITY_TYPE_LEVEL_TEXT[$grade] ?? '',
            'image'     => "https://restapi.amap.com/v3/staticmap?location={$lng},{$lat}&markers=-1,https://file.51kuafu.com/e0/0c/cc0783d7de4fd65c070c14510370bf7dd73969cf2cf804cfe797d5dd23cd.png,0:{$lng},{$lat}&zoom=16&size=646*204&key=" . WangGuiCityByPower::getRandomAmapKey(),
        ], $nearby);
    }

    /**
     * 获得意向区域
     * @param int $shopId
     * @param $lat
     * @param $lng
     * @return array
     */
    public static function intendedCity(int $shopId, $lat, $lng): array
    {
        // 没有经纬度  固定北京
        if (!$lat && !$lng) {
            $lat = 39.904179;
            $lng = 116.407387;
        }

        // 获得开店订单号
        $orderNo = (string)OpenShopMainProcessModel::query()
            ->where('shopId', $shopId)
            ->orderBy('id', 'desc')
            ->value('orderNo');

        if (!strlen($orderNo)) {
            self::throwErr('未查询到您的开业订单号', 403);
        }

        // 获得意向区域
        $userBaseInfoModel = OpenShopUserBaseInfoModel::query()
            ->where('orderNo', $orderNo)
            ->select(['chooseShopProvinceCode', 'chooseShopCityCode', 'chooseShopAddressPrefix'])
            ->first();

        // 获得选址区域
        $siteLocationModel = OpenShopSiteLocationModel::query()
            ->where('source', OpenShopSiteLocationModel::SOURCE_OPEN_SHOP)
            ->where('orderNo', $orderNo)
            ->select(['siteStatus', 'provinceCode', 'cityCode', 'cityArea'])
            ->first();

        if (null == $userBaseInfoModel && null == $siteLocationModel) {
            self::throwErr('未查询到您的基本信息及选址信息', 403);
        }

        $data = [];

        // 未开业拿意向区域
        if (null != $userBaseInfoModel) {
            $data['provinceCode'] = $userBaseInfoModel->chooseShopProvinceCode;
            $data['cityCode']     = $userBaseInfoModel->chooseShopCityCode;

            $addressPrefixArr = explode('-', $userBaseInfoModel->chooseShopAddressPrefix);
            $data['province'] = $addressPrefixArr[0] ?? '';
            $data['city']     = $addressPrefixArr[1] ?? '';
        }

        // 开业后拿选址区域
        if (null != $siteLocationModel && in_array($siteLocationModel->siteStatus, [OpenShopSiteLocationModel::SITE_STATUS_4, OpenShopSiteLocationModel::SITE_STATUS_20, OpenShopSiteLocationModel::SITE_STATUS_21, OpenShopSiteLocationModel::SITE_STATUS_22])) {
            $data['provinceCode'] = $siteLocationModel->provinceCode;
            $data['cityCode']     = $siteLocationModel->cityCode;

            $addressPrefixArr = explode('-', $siteLocationModel->cityArea);
            $data['province'] = $addressPrefixArr[0] ?? '';
            $data['city']     = $addressPrefixArr[1] ?? '';
        }

        // 获得备用经纬度
        if (isset($data['cityCode']) && $data['cityCode'] > 0) {
            $code  = $data['cityCode'];
            $level = AmapRegionBoundaryModel::LEVEL_CITY;
        } else {
            $code  = $data['provinceCode'];
            $level = AmapRegionBoundaryModel::LEVEL_PROVINCE;
        }

        $coordinate = AmapRegionBoundaryModel::query()
            ->where('code', $code)
            ->where('level', $level)
            ->select(['centerLat', 'centerLng', 'boundary'])
            ->first();

        //判断当前用户是否存在意向区域内
        $withinTheRegion = false;
        try {
            if ($lat && $lng && $coordinate != null) {

                // 通过经纬度调用高德接口获得经纬度的地理位置(根据经纬度获得省市区)
                $key     = WangGuiCityByPower::getRandomAmapKey();
                $areaRes = Http::withHeaders(['Content-Type' => 'application/json; charset=utf-8'])
                    ->get(vsprintf(config('area.getReginDetailByLatLng'), [$lng, $lat, $key]))
                    ->json();

                $city     = isset($areaRes['regeocode']['addressComponent']['city']) ? (is_array($areaRes['regeocode']['addressComponent']['city']) ? '' : $areaRes['regeocode']['addressComponent']['city']) : '';
                $province = isset($areaRes['regeocode']['addressComponent']['province']) ? (is_array($areaRes['regeocode']['addressComponent']['province']) ? '' : $areaRes['regeocode']['addressComponent']['province']) : '';

                // 获得城市名称
                if (!mb_strlen($city)) {
                    $city = $province;
                }

                // $cityName = $areaRes['result']['address_component']['city'] ?? '';
                // if (!$cityName) {
                //     $cityName = $areaRes['result']['address_component']['district'] ?? '';
                // }

                // 比较城市名称
                if (substr($data['city'], 0, 2) == substr($city, 0, 2)) {
                    $withinTheRegion = true;
                }

                // 因为高德边界的坐标不是Polygon所需要的  需要特殊处理一下
                // $boundary       = json_decode($coordinate->boundary, true);
                // $formatBoundary = [];
                // foreach ($boundary as $item) {
                //     $formatBoundary[] = [
                //         $item[0],
                //         explode('|', $item[1])[0]
                //     ];
                // }
                //
                // $polygon         = new \League\Geotools\Polygon\Polygon($formatBoundary);
                // $inPolygon       = $polygon->pointInPolygon(new \League\Geotools\Coordinate\Coordinate([$lng, $lat]));
                // $onBoundary      = $polygon->pointOnBoundary(new \League\Geotools\Coordinate\Coordinate([$lng, $lat]));
                // $withinTheRegion = $inPolygon || $onBoundary;
            }
        } catch (\Exception $exception) {

        }

        if ($withinTheRegion) {
            $data['lat'] = $lat;
            $data['lng'] = $lng;
        } else {
            $data['lat'] = (string)optional($coordinate)->centerLat ?: $lat;
            $data['lng'] = (string)optional($coordinate)->centerLng ?: $lng;
        }

        $data['withinTheRegion'] = $withinTheRegion;

        return $data;
    }

    public static function wangguiInfoByLatAndLng($lng, $lat, $type, $radius, $rmsUserId)
    {
        $dotList = Redis::georadius('tiger:wanggui:dot', $lng, $lat, $radius, 'm', ['WITHDIST', 'ASC']);

        // 收藏点位
        $collection = WangguiCollectionDotModel::query()
            ->where('createdByUid', $rmsUserId)
            ->pluck('wgNumber')
            ->toArray();

        $shopDistanceInfo = [];
        foreach ($dotList as $dot) {
            // 过滤不是夸父门店的
            if (substr($dot[0], 0, 4) != 'KFZC') {
                continue;
            }

            // 过滤状态(只保留筹备中和正常营业的+暂停营业)
            if (!in_array(substr($dot[0], 4, 1), [(string)ProgrammingEnum::KF_SHOP_STATUS_BUSINESS, (string)ProgrammingEnum::KF_SHOP_STATUS_PREPARE, (string)ProgrammingEnum::KF_SHOP_STATUS_STOP])) {
                continue;
            }

            $shopDistanceInfo[(int)substr($dot[0], 5, 4)] = (int)$dot[1];
        }

        // 获得门店详情
        $shopList = GuanyuanSyncShopListModel::query()
            ->whereIn('code', array_keys($shopDistanceInfo))
            ->select(['lat', 'lng', 'name', 'code', 'address'])
            ->get()
            ->map(function (GuanyuanSyncShopListModel $guanyuanSyncShopListModel) use ($shopDistanceInfo) {
                return [
                    'lat'      => $guanyuanSyncShopListModel->lat,
                    'lng'      => $guanyuanSyncShopListModel->lng,
                    'name'     => $guanyuanSyncShopListModel->name,
                    'type'     => ProgrammingEnum::PC_TYPE_LIST_HEAD_KF,
                    'code'     => $guanyuanSyncShopListModel->code,
                    'address'  => $guanyuanSyncShopListModel->address,
                    'distance' => $shopDistanceInfo[$guanyuanSyncShopListModel->code] ?? 9999,
                ];
            })->values()->toArray();

        $delPointList = [];
        foreach ($shopList as $shop) {
            $shopDotList = Redis::georadius('tiger:wanggui:dot', $shop['lng'], $shop['lat'], 500, 'm');
            foreach ($shopDotList as $shopDot) {
                $delPointList[] = $shopDot;
            }
        }

        foreach ($dotList as $key => $itemDot) {
            if (in_array($itemDot[0], $delPointList)) {
                unset($dotList[$key]);
            }
        }

        $dotList = array_values($dotList);


        switch ($type) {
            case ProgrammingEnum::PC_TYPE_LIST_HEAD_MALL:
                $mallWgNumbers = [];
                foreach ($dotList as $dot) {
                    // 过滤不是商场的
                    if (substr($dot[0], 0, 2) != 'SC') {
                        continue;
                    }
                    $mallWgNumbers[$dot[0]] = (int)$dot[1];
                }

                $mallWgNumbers = array_slice($mallWgNumbers, 0, 10);

                $data = [];
                SiteLocationMallModel::query()
                    ->where('settle', ProgrammingEnum::SETTLE_STATUS_OFF)
                    ->whereIn('wgNumber', array_keys($mallWgNumbers))
                    ->with([
                        'resourceWithMapRel',
                        'logRel' => function ($q) {
                            $q->with(['resourceRelByCover']);
                        }
                    ])
                    ->chunk(100, function ($siteLocationMalls) use (&$data, $mallWgNumbers, $collection) {
                        foreach ($siteLocationMalls as $siteLocationMallModel) {
                            $auditCover = optional($siteLocationMallModel->resourceWithMapRel)->url ? picturePath($siteLocationMallModel->resourceWithMapRel->url) : SandTableEnum::DEFAULT_COVER_IMAGE_BASIC;
                            $latestAudit = null;
                            if (count($siteLocationMallModel->logRel)) {
                                $latestAudit = collect($siteLocationMallModel->logRel)->sortByDesc('updatedAt')->first();
                                if (count($latestAudit->resourceRelByCover)) {
                                    foreach ($latestAudit->resourceRelByCover as $resourceRelByCover) {
                                        $auditCover = picturePath($resourceRelByCover->url);
                                        break;
                                    }
                                }
                            }

                            $data[] = [
                                'id'             => $siteLocationMallModel->id,
                                'name'           => $siteLocationMallModel->mallName,
                                'wgNumber'       => $siteLocationMallModel->wgNumber,
                                'collection'     => in_array($siteLocationMallModel->wgNumber, $collection),
                                'type'           => ProgrammingEnum::PC_TYPE_LIST_HEAD_MALL,
                                'lat'            => $siteLocationMallModel->lat,
                                'lng'            => $siteLocationMallModel->lng,
                                'shopNum'        => $siteLocationMallModel->shopNum,
                                'boundary'       => [],
                                'grade'          => ProgrammingEnum::PC_GRADE_MAPPING[(int)$siteLocationMallModel->grade] ?? '',
                                'label'          => array_merge((mb_strlen($siteLocationMallModel->topList) ? [$siteLocationMallModel->topList] : [])),
                                'image'          => $auditCover,
                                'special'        => [
                                    [
                                        'name'  => '推荐楼层',
                                        'value' => $siteLocationMallModel->recommendFloor ?: '-',
                                    ], [
                                        'name'  => '店铺总数',
                                        'value' => $siteLocationMallModel->shopTotalCount,
                                    ], [
                                        'name'  => '美食店铺占比',
                                        'value' => $siteLocationMallModel->foodRatio ? ($siteLocationMallModel->foodRatio * 100 . '%') : 0,
                                    ]
                                ],
                                'openPotential'  => (float)optional($latestAudit)->openPotential,
                                'province'       => $siteLocationMallModel->province,
                                'recommendFloor' => $siteLocationMallModel->recommendFloor,
                                'city'           => $siteLocationMallModel->city,
                                'district'       => $siteLocationMallModel->district,
                                'businessCircle' => $siteLocationMallModel->area,
                                'address'        => $siteLocationMallModel->address,
                                'distance'       => $mallWgNumbers[$siteLocationMallModel->wgNumber] ?? 99999,
                            ];
                        }
                    });
                break;
            case ProgrammingEnum::PC_TYPE_LIST_HEAD_STREET:
                $streetWgNumbers = [];
                foreach ($dotList as $dot) {
                    // 过滤不是街道的
                    if (substr($dot[0], 0, 2) != 'JD') {
                        continue;
                    }
                    $streetWgNumbers[$dot[0]] = (int)$dot[1];
                }

                $streetWgNumbers = array_slice($streetWgNumbers, 0, 10);

                $data = [];

                MapNationalStreetModel::query()
                    ->where('settle', ProgrammingEnum::SETTLE_STATUS_OFF)
                    ->whereIn('wgNumber', array_keys($streetWgNumbers))
                    ->with([
                        'resourceWithMapRel',
                        'logRel' => function ($q) {
                            $q->with(['resourceRelByCover']);
                        }
                    ])
                    ->chunk(100, function ($mapNationalStreetModels) use (&$data, $streetWgNumbers, $collection) {
                        foreach ($mapNationalStreetModels as $mapNationalStreetModel) {
                            $auditCover = optional($mapNationalStreetModel->resourceWithMapRel)->url ? picturePath($mapNationalStreetModel->resourceWithMapRel->url) : SandTableEnum::DEFAULT_COVER_IMAGE_BASIC;
                            $latestAudit = null;
                            if (count($mapNationalStreetModel->logRel)) {
                                $latestAudit = collect($mapNationalStreetModel->logRel)->sortByDesc('updatedAt')->first();
                                if (count($latestAudit->resourceRelByCover)) {
                                    foreach ($latestAudit->resourceRelByCover as $resourceRelByCover) {
                                        $auditCover = picturePath($resourceRelByCover->url);
                                        break;
                                    }
                                }
                            }
                            $data[] = [
                                'id'            => $mapNationalStreetModel->id,
                                'name'          => $mapNationalStreetModel->address,
                                'wgNumber'      => $mapNationalStreetModel->wgNumber,
                                'collection'    => in_array($mapNationalStreetModel->wgNumber, $collection),
                                'type'          => ProgrammingEnum::PC_TYPE_LIST_HEAD_STREET,
                                'lat'           => $mapNationalStreetModel->lat,
                                'lng'           => $mapNationalStreetModel->lng,
                                'shopNum'       => $mapNationalStreetModel->shopNum,
                                'boundary'      => json_decode($mapNationalStreetModel->coords, true),
                                'grade'         => ProgrammingEnum::PC_GRADE_MAPPING[(int)$mapNationalStreetModel->grade] ?? '',
                                'label'         => [],
                                'image'         => $auditCover,
                                'special'       => [],
                                'openPotential' => (float)optional($latestAudit)->openPotential,
                                'province'      => $mapNationalStreetModel->province,
                                'city'          => $mapNationalStreetModel->city,
                                'district'      => $mapNationalStreetModel->district,
                                'address'       => $mapNationalStreetModel->address,
                                'distance'      => $streetWgNumbers[$mapNationalStreetModel->wgNumber] ?? 99999,
                            ];
                        }
                    });
                break;
            case ProgrammingEnum::PC_TYPE_LIST_HEAD_COMMUNITY:
                $communityWgNumbers = [];
                foreach ($dotList as $dot) {
                    // 过滤不是街道的
                    if (substr($dot[0], 0, 2) != 'SQ') {
                        continue;
                    }
                    $communityWgNumbers[$dot[0]] = (int)$dot[1];
                }

                $communityWgNumbers = array_slice($communityWgNumbers, 0, 10);

                MapNationalCommunityModel::query()
                    ->where('settle', ProgrammingEnum::SETTLE_STATUS_OFF)
                    ->whereIn('wgNumber', array_keys($communityWgNumbers))
                    ->with([
                        'resourceWithMapRel',
                        'logRel' => function ($q) {
                            $q->with(['resourceRelByCover']);
                        }
                    ])
                    ->chunk(100, function ($mapNationalStreetModels) use (&$data, $communityWgNumbers, $collection) {
                        foreach ($mapNationalStreetModels as $mapNationalStreetModel) {
                            $auditCover = optional($mapNationalStreetModel->resourceWithMapRel)->url ? picturePath($mapNationalStreetModel->resourceWithMapRel->url) : SandTableEnum::DEFAULT_COVER_IMAGE_BASIC;
                            $latestAudit = null;
                            if (count($mapNationalStreetModel->logRel)) {
                                $latestAudit = collect($mapNationalStreetModel->logRel)->sortByDesc('updatedAt')->first();
                                if (count($latestAudit->resourceRelByCover)) {
                                    foreach ($latestAudit->resourceRelByCover as $resourceRelByCover) {
                                        $auditCover = picturePath($resourceRelByCover->url);
                                        break;
                                    }
                                }
                            }
                            $data[] = [
                                'id'            => $mapNationalStreetModel->id,
                                'name'          => $mapNationalStreetModel->address,
                                'type'          => ProgrammingEnum::PC_TYPE_LIST_HEAD_COMMUNITY,
                                'wgNumber'      => $mapNationalStreetModel->wgNumber,
                                'collection'    => in_array($mapNationalStreetModel->wgNumber, $collection),
                                'lat'           => $mapNationalStreetModel->lat,
                                'lng'           => $mapNationalStreetModel->lng,
                                'shopNum'       => $mapNationalStreetModel->shopNum,
                                'boundary'      => json_decode($mapNationalStreetModel->coords, true),
                                'grade'         => ProgrammingEnum::PC_GRADE_MAPPING[(int)$mapNationalStreetModel->grade] ?? '',
                                'label'         => [],
                                'image'         => $auditCover,
                                'special'       => [],
                                'openPotential' => (float)optional($latestAudit)->openPotential,
                                'province'      => $mapNationalStreetModel->province,
                                'city'          => $mapNationalStreetModel->city,
                                'district'      => $mapNationalStreetModel->district,
                                'address'       => $mapNationalStreetModel->address,
                                'distance'      => $communityWgNumbers[$mapNationalStreetModel->wgNumber] ?? 99999,
                            ];
                        }
                    });
                break;
            case ProgrammingEnum::PC_TYPE_LIST_HEAD_UNIVERSITIES:
                $universitieWgNumbers = [];
                foreach ($dotList as $dot) {
                    // 过滤不是高校的
                    if (substr($dot[0], 0, 2) != 'GX') {
                        continue;
                    }
                    $universitieWgNumbers[$dot[0]] = (int)$dot[1];
                }

                $universitieWgNumbers = array_slice($universitieWgNumbers, 0, 10);

                MapNationalUniversitiesModel::query()
                    ->where('settle', ProgrammingEnum::SETTLE_STATUS_OFF)
                    ->whereIn('wgNumber', array_keys($universitieWgNumbers))
                    ->with([
                        'resourceWithMapRel',
                        'logRel' => function ($q) {
                            $q->with(['resourceRelByCover']);
                        }
                    ])
                    ->chunk(100, function ($mapNationalUniversitiesModels) use (&$data, $universitieWgNumbers, $collection) {
                        foreach ($mapNationalUniversitiesModels as $mapNationalUniversitiesModel) {
                            $auditCover = optional($mapNationalUniversitiesModel->resourceWithMapRel)->url ? picturePath($mapNationalUniversitiesModel->resourceWithMapRel->url) : SandTableEnum::DEFAULT_COVER_IMAGE_BASIC;
                            $latestAudit = null;
                            if (count($mapNationalUniversitiesModel->logRel)) {
                                $latestAudit = collect($mapNationalUniversitiesModel->logRel)->sortByDesc('updatedAt')->first();
                                if (count($latestAudit->resourceRelByCover)) {
                                    foreach ($latestAudit->resourceRelByCover as $resourceRelByCover) {
                                        $auditCover = picturePath($resourceRelByCover->url);
                                        break;
                                    }
                                }
                            }
                            $data[] = [
                                'id'            => $mapNationalUniversitiesModel->id,
                                'name'          => $mapNationalUniversitiesModel->name,
                                'type'          => ProgrammingEnum::PC_TYPE_LIST_HEAD_UNIVERSITIES,
                                'wgNumber'      => $mapNationalUniversitiesModel->wgNumber,
                                'collection'    => in_array($mapNationalUniversitiesModel->wgNumber, $collection),
                                'lat'           => $mapNationalUniversitiesModel->lat,
                                'lng'           => $mapNationalUniversitiesModel->lon,
                                'shopNum'       => $mapNationalUniversitiesModel->shopNum,
                                'boundary'      => [],
                                'grade'         => ProgrammingEnum::PC_GRADE_MAPPING[(int)$mapNationalUniversitiesModel->grade] ?? '',
                                'label'         => [],
                                'image'         => $auditCover,
                                'special'       => [],
                                'openPotential' => (float)optional($latestAudit)->openPotential,
                                'province'      => $mapNationalUniversitiesModel->province,
                                'city'          => $mapNationalUniversitiesModel->city,
                                'district'      => $mapNationalUniversitiesModel->district,
                                'address'       => $mapNationalUniversitiesModel->address,
                                'distance'      => $universitieWgNumbers[$mapNationalUniversitiesModel->wgNumber] ?? 99999,
                            ];
                        }
                    });
                break;
            case ProgrammingEnum::PC_TYPE_LIST_HEAD_PARK:
                $parkWgNumbers = [];
                foreach ($dotList as $dot) {
                    // 过滤不是产业园的
                    if (substr($dot[0], 0, 3) != 'CYY') {
                        continue;
                    }
                    $parkWgNumbers[$dot[0]] = (int)$dot[1];
                }

                $data = [];
                MapNationalIndustrialParkModel::query()
                    ->where('settle', ProgrammingEnum::SETTLE_STATUS_OFF)
                    ->whereIn('wgNumber', array_keys($parkWgNumbers))
                    ->with([
                        'resourceWithMapRel',
                        'logRel' => function ($q) {
                            $q->with(['resourceRelByCover']);
                        }
                    ])
                    ->chunk(100, function ($mapNationalIndustrialParkModels) use (&$data, $parkWgNumbers, $collection) {
                        foreach ($mapNationalIndustrialParkModels as $mapNationalIndustrialParkModel) {
                            $auditCover = optional($mapNationalIndustrialParkModel->resourceWithMapRel)->url ? picturePath($mapNationalIndustrialParkModel->resourceWithMapRel->url) : SandTableEnum::DEFAULT_COVER_IMAGE_BASIC;
                            if (count($mapNationalIndustrialParkModel->logRel)) {
                                $latestAudit = collect($mapNationalIndustrialParkModel->logRel)->sortByDesc('updatedAt')->first();
                                if (count($latestAudit->resourceRelByCover)) {
                                    foreach ($latestAudit->resourceRelByCover as $resourceRelByCover) {
                                        $auditCover = picturePath($resourceRelByCover->url);
                                        break;
                                    }
                                }
                            }
                            $data[] = [
                                'id'         => $mapNationalIndustrialParkModel->id,
                                'name'       => $mapNationalIndustrialParkModel->name,
                                'wgNumber'   => $mapNationalIndustrialParkModel->wgNumber,
                                'collection' => in_array($mapNationalIndustrialParkModel->wgNumber, $collection),
                                'type'       => ProgrammingEnum::PC_TYPE_LIST_HEAD_PARK,
                                'lat'        => $mapNationalIndustrialParkModel->lat,
                                'lng'        => $mapNationalIndustrialParkModel->lon,
                                'shopNum'    => $mapNationalIndustrialParkModel->shopNum,
                                'boundary'   => [],
                                'grade'      => ProgrammingEnum::PC_GRADE_MAPPING[(int)$mapNationalIndustrialParkModel->grade] ?? '',
                                'label'      => [],
                                'image'      => $auditCover,
                                'special'    => [],
                                'province'   => $mapNationalIndustrialParkModel->province,
                                'city'       => $mapNationalIndustrialParkModel->city,
                                'district'   => $mapNationalIndustrialParkModel->district,
                                'address'    => $mapNationalIndustrialParkModel->name,
                                'distance'   => $parkWgNumbers[$mapNationalIndustrialParkModel->wgNumber] ?? 99999
                            ];
                        }
                    });
                break;
            case ProgrammingEnum::PC_TYPE_LIST_HEAD_RESIDENCE:
                $communityWgNumbers = [];
                foreach ($dotList as $dot) {
                    // 过滤不是小区的
                    if (substr($dot[0], 0, 4) != 'XQ99') {
                        continue;
                    }
                    $communityWgNumbers[(int)substr($dot[0], 4)] = (int)$dot[1];
                }
                $data = [];

                CityResidencePriceModel::query()
                    ->whereIn('id', array_keys($communityWgNumbers))
                    ->with([
                        'resourceWithMapRel',
                    ])
                    ->chunk(100, function ($cityResidencePriceModels) use (&$data, $communityWgNumbers, $collection) {
                        foreach ($cityResidencePriceModels as $cityResidencePriceModel) {
                            $data[] = [
                                'id'         => $cityResidencePriceModel->id,
                                'name'       => $cityResidencePriceModel->name,
                                'wgNumber'   => $cityResidencePriceModel->wgNumber,
                                'collection' => in_array($cityResidencePriceModel->wgNumber, $collection),
                                'type'       => ProgrammingEnum::PC_TYPE_LIST_HEAD_RESIDENCE,
                                'lat'        => $cityResidencePriceModel->centerLatitude,
                                'lng'        => $cityResidencePriceModel->centerLongitude,
                                'boundary'   => [],
                                'grade'      => '',
                                'label'      => [],
                                'head'       => '',
                                'image'      => optional($cityResidencePriceModel->resourceWithMapRel)->url ? picturePath($cityResidencePriceModel->resourceWithMapRel->url) : SandTableEnum::DEFAULT_COVER_IMAGE_BASIC,
                                'special'    => [],
                                'province'   => $cityResidencePriceModel->province,
                                'city'       => $cityResidencePriceModel->city,
                                'district'   => $cityResidencePriceModel->district,
                                'address'    => $cityResidencePriceModel->name,
                                'distance'   => $communityWgNumbers[$cityResidencePriceModel->id] ?? 99999,
                            ];
                        }
                    });
                break;
            case ProgrammingEnum::PC_TYPE_LIST_HEAD_COMPETITION:
                $competitionWgNumbers = [];
                foreach ($dotList as $dot) {
                    // 过滤不是竞品的
                    if (substr($dot[0], 0, 2) != 'PP') {
                        continue;
                    }
                    $competitionWgNumbers[$dot[0]] = (int)$dot[1];
                }

                $data = [];
                MapNationalBrandShopModel::query()
                    ->whereIn('wgNumber', array_keys($competitionWgNumbers))
                    ->whereIn('brand', ProgrammingEnum::BRAND_SAND_TABLE_COMPETITIVE_PRODUCTS_MAPPING)
                    ->with([
                        'resourceWithMapRel',
                    ])
                    ->chunk(100, function ($mapNationalBrandShopModels) use (&$data, $competitionWgNumbers, $collection) {
                        foreach ($mapNationalBrandShopModels as $mapNationalBrandShopModel) {

                            $special = [];
                            if ($mapNationalBrandShopModel->openingTime) {
                                $special[] = [
                                    'name'  => '开业时间',
                                    'value' => $mapNationalBrandShopModel->openingTime ?: '-',
                                ];
                            }

                            $data[] = [
                                'id'         => $mapNationalBrandShopModel->id,
                                'name'       => strpos($mapNationalBrandShopModel->name, $mapNationalBrandShopModel->brand) !== false ? $mapNationalBrandShopModel->name : $mapNationalBrandShopModel->brand . $mapNationalBrandShopModel->name,
                                'wgNumber'   => $mapNationalBrandShopModel->wgNumber,
                                'collection' => in_array($mapNationalBrandShopModel->wgNumber, $collection),
                                'brand'      => $mapNationalBrandShopModel->brand,
                                'key'        => ProgrammingEnum::BRAND_SHOP_MAPPING[$mapNationalBrandShopModel->brand] ?? '',
                                'type'       => ProgrammingEnum::PC_TYPE_LIST_HEAD_COMPETITION,
                                'lat'        => $mapNationalBrandShopModel->lat,
                                'lng'        => $mapNationalBrandShopModel->lon,
                                'boundary'   => [],
                                'grade'      => '',
                                'label'      => [],
                                'head'       => '',
                                'image'      => (optional($mapNationalBrandShopModel->resourceWithMapRel)->url ? picturePath($mapNationalBrandShopModel->resourceWithMapRel->url) : '') ?: (ProgrammingEnum::BRAND_SHOP_LOG_IMAGE_MAPPING[$mapNationalBrandShopModel->brand] ?? SandTableEnum::DEFAULT_COVER_IMAGE_BASIC),
                                'special'    => $special,
                                'province'   => $mapNationalBrandShopModel->province,
                                'city'       => $mapNationalBrandShopModel->city,
                                'district'   => $mapNationalBrandShopModel->district,
                                'address'    => $mapNationalBrandShopModel->address,
                                'distance'   => $competitionWgNumbers[$mapNationalBrandShopModel->wgNumber] ?? 99999,
                            ];
                        }
                    });
                break;
            case ProgrammingEnum::PC_TYPE_LIST_HEAD_COMPLEMENT:
                $complementWgNumbers = [];
                foreach ($dotList as $dot) {
                    // 过滤不是互补品的
                    if (substr($dot[0], 0, 2) != 'PP') {
                        continue;
                    }
                    $complementWgNumbers[$dot[0]] = (int)$dot[1];
                }

                $data = [];
                MapNationalBrandShopModel::query()
                    ->whereIn('wgNumber', array_keys($complementWgNumbers))
                    ->whereIn('brand', ProgrammingEnum::BRAND_SAND_TABLE_COMPLEMENTARY_PRODUCTS_MAPPING)
                    ->with([
                        'resourceWithMapRel',
                    ])
                    ->chunk(100, function ($mapNationalBrandShopModels) use (&$data, $complementWgNumbers, $collection) {
                        foreach ($mapNationalBrandShopModels as $mapNationalBrandShopModel) {
                            $special = [];
                            if ($mapNationalBrandShopModel->openingTime) {
                                $special[] = [
                                    'name'  => '开业时间',
                                    'value' => $mapNationalBrandShopModel->openingTime ?: '-',
                                ];
                            }

                            $data[] = [
                                'id'         => $mapNationalBrandShopModel->id,
                                'name'       => strpos($mapNationalBrandShopModel->name, $mapNationalBrandShopModel->brand) !== false ? $mapNationalBrandShopModel->name : $mapNationalBrandShopModel->brand . $mapNationalBrandShopModel->name,
                                'wgNumber'   => $mapNationalBrandShopModel->wgNumber,
                                'collection' => in_array($mapNationalBrandShopModel->wgNumber, $collection),
                                'brand'      => $mapNationalBrandShopModel->brand,
                                'key'        => ProgrammingEnum::BRAND_SHOP_MAPPING[$mapNationalBrandShopModel->brand] ?? '',
                                'type'       => ProgrammingEnum::PC_TYPE_LIST_HEAD_COMPLEMENT,
                                'lat'        => $mapNationalBrandShopModel->lat,
                                'lng'        => $mapNationalBrandShopModel->lon,
                                'boundary'   => [],
                                'grade'      => '',
                                'label'      => [],
                                'head'       => '',
                                'image'      => (optional($mapNationalBrandShopModel->resourceWithMapRel)->url ? picturePath($mapNationalBrandShopModel->resourceWithMapRel->url) : '') ?: (ProgrammingEnum::BRAND_SHOP_LOG_IMAGE_MAPPING[$mapNationalBrandShopModel->brand] ?? SandTableEnum::DEFAULT_COVER_IMAGE_BASIC),
                                'special'    => $special,
                                'province'   => $mapNationalBrandShopModel->province,
                                'city'       => $mapNationalBrandShopModel->city,
                                'district'   => $mapNationalBrandShopModel->district,
                                'address'    => $mapNationalBrandShopModel->address,
                                'distance'   => $complementWgNumbers[$mapNationalBrandShopModel->wgNumber] ?? 99999,
                            ];
                        }
                    });
                break;
            default:
                $data = [];
        }

        return ['list' => collect($data)->sortBy('distance')->values()->toArray()];
    }


    /**
     * 根据经纬度获得高德的静态图片
     * @param $lat
     * @param $lng
     * @return string
     */
    public static function getAmapImage($lat, $lng): string
    {
        if (!$lat || !$lng) {
            return '';
        }
        return "https://restapi.amap.com/v3/staticmap?location={$lng},{$lat}&markers=-1,https://file.51kuafu.com/e0/0c/cc0783d7de4fd65c070c14510370bf7dd73969cf2cf804cfe797d5dd23cd.png,0:{$lng},{$lat}&zoom=16&size=204*204&key=" . WangGuiCityByPower::getRandomAmapKey();
    }

    public static function pointInfoByLatAndLng($lng, $lat, string $type, int $radius, string $searchInput, int $cityCode, $rmsUserId, $id): array
    {
        $isSearch = false;
        if (strlen($searchInput) && $cityCode) {
            $isSearch = true;
            $searchResult = self::searchDots($searchInput, $cityCode);
            $dotList = [];
            foreach ($searchResult as $res) {
                foreach ($res as $item) {
                    $dotList[] = [
                        $item,
                        0
                    ];
                }
            }
        } else {
            if (!$lat || !$lng) {
                self::throwErr('经纬度传入错误');
            }
            $dotList = Redis::georadius('tiger:wanggui:dot', $lng, $lat, ($radius + 1000), 'm', ['WITHDIST', 'ASC']);
        }

        // 点位信息
        $data = [];

        // 收藏点位
        $collection = WangguiCollectionDotModel::query()
            ->where('createdByUid', $rmsUserId)
            ->pluck('wgNumber')
            ->toArray();

        $collectionList = [];

        $shopDistanceInfo = [];
        foreach ($dotList as $dot) {
            // 过滤不是夸父门店的
            if (substr($dot[0], 0, 4) != 'KFZC') {
                continue;
            }

            // 过滤状态(只保留筹备中和正常营业的)
            if (!in_array(substr($dot[0], 4, 1), [(string)ProgrammingEnum::KF_SHOP_STATUS_BUSINESS, (string)ProgrammingEnum::KF_SHOP_STATUS_PREPARE, (string)ProgrammingEnum::KF_SHOP_STATUS_STOP])) {
                continue;
            }

            $shopDistanceInfo[(int)substr($dot[0], 5, 4)] = (int)$dot[1];
        }

        // 获得门店详情
        $shopList = GuanyuanSyncShopListModel::query()
            ->whereIn('code', array_keys($shopDistanceInfo))
            ->select(['lat', 'lng', 'name', 'code', 'address'])
            ->get()
            ->map(function (GuanyuanSyncShopListModel $guanyuanSyncShopListModel) use ($shopDistanceInfo) {
                return [
                    'lat'      => $guanyuanSyncShopListModel->lat,
                    'lng'      => $guanyuanSyncShopListModel->lng,
                    'name'     => $guanyuanSyncShopListModel->name,
                    'type'     => ProgrammingEnum::PC_TYPE_LIST_HEAD_KF,
                    'code'     => $guanyuanSyncShopListModel->code,
                    'address'  => $guanyuanSyncShopListModel->address,
                    'distance' => $shopDistanceInfo[$guanyuanSyncShopListModel->code] ?? 9999,
                ];
            })->values()->toArray();

        $delPointList = [];
        foreach ($shopList as $shop) {
            $shopDotList = Redis::georadius('tiger:wanggui:dot', $shop['lng'], $shop['lat'], 500, 'm');
            foreach ($shopDotList as $shopDot) {
                $delPointList[] = $shopDot;
            }
        }

        foreach ($dotList as $key => $itemDot) {
            if (in_array($itemDot[0], $delPointList)) {
                unset($dotList[$key]);
            }
        }

        foreach ($dotList as $value) {
            if (substr($value[0], 0, 2) == 'SC') {
                $circle = SiteLocationMallModel::query()
                    ->where('wgNumber', $value[0])
                    ->first();
                break;
            }
            if (substr($value[0], 0, 2) == 'JD') {
                $circle = MapNationalStreetModel::query()
                    ->where('wgNumber', $value[0])
                    ->first();
                break;
            }
            if (substr($value[0], 0, 2) == 'SQ') {
                $circle = MapNationalCommunityModel::query()
                    ->where('wgNumber', $value[0])
                    ->first();
                break;
            }
            if (substr($value[0], 0, 2) == 'GX') {
                $circle = MapNationalUniversitiesModel::query()
                    ->where('wgNumber', $value[0])
                    ->first();
                break;
            }
        }

        if (isset($circle) && $circle != null) {
            if ($isSearch) {
                $inArrayDotList = array_map(function ($item) {
                    return $item[0];
                }, $dotList);
                // 要筛选出搜索的
                $dotAllList = Redis::georadius('tiger:wanggui:dot', $circle->lng, $circle->lat, $radius, 'm', ['WITHDIST', 'ASC']);
                $dotList = collect($dotAllList)->map(function ($dot) use ($inArrayDotList) {
                    if (isset($dot[0]) && in_array($dot[0], $inArrayDotList)) {
                        return $dot;
                    } else {
                        return null;
                    }
                })->filter()->values()->toArray();
            } else {
                $dotList = Redis::georadius('tiger:wanggui:dot', $circle->lng, $circle->lat, $radius, 'm', ['WITHDIST', 'ASC']);
            }
        }

        foreach ($dotList as $key => $itemDot) {
            if (in_array($itemDot[0], $delPointList)) {
                unset($dotList[$key]);
            }
        }

        $dotList = array_values($dotList);

        $typeArr = explode(',', $type);

        if (in_array(ProgrammingEnum::PC_TYPE_LIST_HEAD_MALL, $typeArr) || !strlen($type)) {
            $mallWgNumbers = [];
            foreach ($dotList as $dot) {
                // 过滤不是商场的
                if (substr($dot[0], 0, 2) != 'SC') {
                    continue;
                }
                $mallWgNumbers[$dot[0]] = (int)$dot[1];
            }

            $mallWgNumbers = array_slice($mallWgNumbers, 0, 10);

            SiteLocationMallModel::query()
                ->where('settle', ProgrammingEnum::SETTLE_STATUS_OFF)
                ->whereIn('wgNumber', array_keys($mallWgNumbers))
                ->with([
                    'resourceWithMapRel',
                    'logRel' => function ($q) {
                        $q->with(['resourceRelByCover']);
                    }
                ])
                ->chunk(100, function ($siteLocationMalls) use (&$data, $mallWgNumbers, $collection, &$collectionList) {
                    foreach ($siteLocationMalls as $siteLocationMallModel) {
                        $auditCover = optional($siteLocationMallModel->resourceWithMapRel)->url ? picturePath($siteLocationMallModel->resourceWithMapRel->url) : SandTableEnum::DEFAULT_COVER_IMAGE_BASIC;
                        $latestAudit = null;
                        if (count($siteLocationMallModel->logRel)) {
                            $latestAudit = collect($siteLocationMallModel->logRel)->sortByDesc('updatedAt')->first();
                            if (count($latestAudit->resourceRelByCover)) {
                                foreach ($latestAudit->resourceRelByCover as $resourceRelByCover) {
                                    $auditCover = picturePath($resourceRelByCover->url);
                                    break;
                                }
                            }
                        }

                        $temp = [
                            'id'             => $siteLocationMallModel->id,
                            'name'           => $siteLocationMallModel->mallName,
                            'type'           => ProgrammingEnum::PC_TYPE_LIST_HEAD_MALL,
                            'wgNumber'       => $siteLocationMallModel->wgNumber,
                            'collection'     => $collectionRes = in_array($siteLocationMallModel->wgNumber, $collection),
                            'lat'            => $siteLocationMallModel->lat,
                            'lng'            => $siteLocationMallModel->lng,
                            'shopNum'        => $siteLocationMallModel->shopNum,
                            'boundary'       => [],
                            'grade'          => ProgrammingEnum::PC_GRADE_MAPPING[(int)$siteLocationMallModel->grade] ?? '',
                            'label'          => array_merge((mb_strlen($siteLocationMallModel->topList) ? [$siteLocationMallModel->topList] : [])),
                            'image'          => $auditCover,
                            'special'        => [
                                [
                                    'name'  => '推荐楼层',
                                    'value' => $siteLocationMallModel->recommendFloor ?: '-',
                                ], [
                                    'name'  => '店铺总数',
                                    'value' => $siteLocationMallModel->shopTotalCount,
                                ], [
                                    'name'  => '美食店铺占比',
                                    'value' => $siteLocationMallModel->foodRatio ? ($siteLocationMallModel->foodRatio * 100 . '%') : 0,
                                ]
                            ],
                            'openPotential'  => (float)optional($latestAudit)->openPotential,
                            'province'       => $siteLocationMallModel->province,
                            'recommendFloor' => $siteLocationMallModel->recommendFloor,
                            'city'           => $siteLocationMallModel->city,
                            'district'       => $siteLocationMallModel->district,
                            'businessCircle' => $siteLocationMallModel->area,
                            'address'        => $siteLocationMallModel->address,
                            'distance'       => $mallWgNumbers[$siteLocationMallModel->wgNumber] ?? 99999,
                        ];

                        if ($collectionRes) {
                            $collectionList[] = $temp;
                        }

                        $data[] = $temp;
                    }
                });
        }
        if (in_array(ProgrammingEnum::PC_TYPE_LIST_HEAD_STREET, $typeArr) || !strlen($type)) {
            $streetWgNumbers = [];
            foreach ($dotList as $dot) {
                // 过滤不是街道的
                if (substr($dot[0], 0, 2) != 'JD') {
                    continue;
                }
                $streetWgNumbers[$dot[0]] = (int)$dot[1];
            }

            $streetWgNumbers = array_slice($streetWgNumbers, 0, 10);

            MapNationalStreetModel::query()
                ->where('settle', ProgrammingEnum::SETTLE_STATUS_OFF)
                ->whereIn('wgNumber', array_keys($streetWgNumbers))
                ->with([
                    'resourceWithMapRel',
                    'logRel' => function ($q) {
                        $q->with(['resourceRelByCover']);
                    }
                ])
                ->chunk(100, function ($mapNationalStreetModels) use (&$data, $streetWgNumbers, $collection, &$collectionList) {
                    foreach ($mapNationalStreetModels as $mapNationalStreetModel) {
                        $auditCover  = optional($mapNationalStreetModel->resourceWithMapRel)->url ? picturePath($mapNationalStreetModel->resourceWithMapRel->url) : SandTableEnum::DEFAULT_COVER_IMAGE_BASIC;
                        $latestAudit = null;
                        if (count($mapNationalStreetModel->logRel)) {
                            $latestAudit = collect($mapNationalStreetModel->logRel)->sortByDesc('updatedAt')->first();
                            if (count($latestAudit->resourceRelByCover)) {
                                foreach ($latestAudit->resourceRelByCover as $resourceRelByCover) {
                                    $auditCover = picturePath($resourceRelByCover->url);
                                    break;
                                }
                            }
                        }
                        $temp = [
                            'id'            => $mapNationalStreetModel->id,
                            'name'          => $mapNationalStreetModel->address,
                            'type'          => ProgrammingEnum::PC_TYPE_LIST_HEAD_STREET,
                            'wgNumber'      => $mapNationalStreetModel->wgNumber,
                            'collection'    => $collectionRes = in_array($mapNationalStreetModel->wgNumber, $collection),
                            'lat'           => $mapNationalStreetModel->lat,
                            'lng'           => $mapNationalStreetModel->lng,
                            'shopNum'       => $mapNationalStreetModel->shopNum,
                            'boundary'      => json_decode($mapNationalStreetModel->coords, true),
                            'grade'         => ProgrammingEnum::PC_GRADE_MAPPING[(int)$mapNationalStreetModel->grade] ?? '',
                            'label'         => [],
                            'image'         => $auditCover,
                            'special'       => [],
                            'openPotential' => (float)optional($latestAudit)->openPotential,
                            'province'      => $mapNationalStreetModel->province,
                            'city'          => $mapNationalStreetModel->city,
                            'district'      => $mapNationalStreetModel->district,
                            'address'       => $mapNationalStreetModel->address,
                            'distance'      => $streetWgNumbers[$mapNationalStreetModel->wgNumber] ?? 99999,
                        ];

                        if ($collectionRes) {
                            $collectionList[] = $temp;
                        }

                        $data[] = $temp;
                    }
                });
        }
        if (in_array(ProgrammingEnum::PC_TYPE_LIST_HEAD_COMMUNITY, $typeArr) || !strlen($type)) {
            $communityWgNumbers = [];
            foreach ($dotList as $dot) {
                // 过滤不是社区的
                if (substr($dot[0], 0, 2) != 'SQ') {
                    continue;
                }
                $communityWgNumbers[$dot[0]] = (int)$dot[1];
            }

            $communityWgNumbers = array_slice($communityWgNumbers, 0, 10);

            MapNationalCommunityModel::query()
                ->where('settle', ProgrammingEnum::SETTLE_STATUS_OFF)
                ->whereIn('wgNumber', array_keys($communityWgNumbers))
                ->with([
                    'resourceWithMapRel',
                    'logRel' => function ($q) {
                        $q->with(['resourceRelByCover']);
                    }
                ])
                ->chunk(100, function ($mapNationalStreetModels) use (&$data, $communityWgNumbers, $collection, &$collectionList) {
                    foreach ($mapNationalStreetModels as $mapNationalStreetModel) {
                        $auditCover = optional($mapNationalStreetModel->resourceWithMapRel)->url ? picturePath($mapNationalStreetModel->resourceWithMapRel->url) : SandTableEnum::DEFAULT_COVER_IMAGE_BASIC;
                        $latestAudit = null;
                        if (count($mapNationalStreetModel->logRel)) {
                            $latestAudit = collect($mapNationalStreetModel->logRel)->sortByDesc('updatedAt')->first();
                            if (count($latestAudit->resourceRelByCover)) {
                                foreach ($latestAudit->resourceRelByCover as $resourceRelByCover) {
                                    $auditCover = picturePath($resourceRelByCover->url);
                                    break;
                                }
                            }
                        }
                        $temp = [
                            'id'            => $mapNationalStreetModel->id,
                            'name'          => $mapNationalStreetModel->address,
                            'type'          => ProgrammingEnum::PC_TYPE_LIST_HEAD_COMMUNITY,
                            'wgNumber'      => $mapNationalStreetModel->wgNumber,
                            'collection'    => $collectionRes = in_array($mapNationalStreetModel->wgNumber, $collection),
                            'lat'           => $mapNationalStreetModel->lat,
                            'lng'           => $mapNationalStreetModel->lng,
                            'shopNum'       => $mapNationalStreetModel->shopNum,
                            'boundary'      => json_decode($mapNationalStreetModel->coords, true),
                            'grade'         => ProgrammingEnum::PC_GRADE_MAPPING[(int)$mapNationalStreetModel->grade] ?? '',
                            'label'         => [],
                            'image'         => $auditCover,
                            'special'       => [],
                            'openPotential' => (float)optional($latestAudit)->openPotential,
                            'province'      => $mapNationalStreetModel->province,
                            'city'          => $mapNationalStreetModel->city,
                            'district'      => $mapNationalStreetModel->district,
                            'address'       => $mapNationalStreetModel->address,
                            'distance'      => $communityWgNumbers[$mapNationalStreetModel->wgNumber] ?? 99999,
                        ];

                        if ($collectionRes) {
                            $collectionList[] = $temp;
                        }

                        $data[] = $temp;
                    }
                });
        }
        if (in_array(ProgrammingEnum::PC_TYPE_LIST_HEAD_UNIVERSITIES, $typeArr) || !strlen($type)) {
            $universitieWgNumbers = [];
            foreach ($dotList as $dot) {
                // 过滤不是高校的
                if (substr($dot[0], 0, 2) != 'GX') {
                    continue;
                }
                $universitieWgNumbers[$dot[0]] = (int)$dot[1];
            }

            $universitieWgNumbers = array_slice($universitieWgNumbers, 0, 10);

            MapNationalUniversitiesModel::query()
                ->where('settle', ProgrammingEnum::SETTLE_STATUS_OFF)
                ->whereIn('wgNumber', array_keys($universitieWgNumbers))
                ->with([
                    'resourceWithMapRel',
                    'logRel' => function ($q) {
                        $q->with(['resourceRelByCover']);
                    }
                ])
                ->chunk(100, function ($mapNationalUniversitiesModels) use (&$data, $universitieWgNumbers, $collection, &$collectionList) {
                    foreach ($mapNationalUniversitiesModels as $mapNationalUniversitiesModel) {
                        $auditCover = optional($mapNationalUniversitiesModel->resourceWithMapRel)->url ? picturePath($mapNationalUniversitiesModel->resourceWithMapRel->url) : SandTableEnum::DEFAULT_COVER_IMAGE_BASIC;
                        $latestAudit = null;
                        if (count($mapNationalUniversitiesModel->logRel)) {
                            $latestAudit = collect($mapNationalUniversitiesModel->logRel)->sortByDesc('updatedAt')->first();
                            if (count($latestAudit->resourceRelByCover)) {
                                foreach ($latestAudit->resourceRelByCover as $resourceRelByCover) {
                                    $auditCover = picturePath($resourceRelByCover->url);
                                    break;
                                }
                            }
                        }
                        $temp = [
                            'id'            => $mapNationalUniversitiesModel->id,
                            'name'          => $mapNationalUniversitiesModel->name,
                            'type'          => ProgrammingEnum::PC_TYPE_LIST_HEAD_UNIVERSITIES,
                            'wgNumber'      => $mapNationalUniversitiesModel->wgNumber,
                            'collection'    => $collectionRes = in_array($mapNationalUniversitiesModel->wgNumber, $collection),
                            'lat'           => $mapNationalUniversitiesModel->lat,
                            'lng'           => $mapNationalUniversitiesModel->lon,
                            'shopNum'       => $mapNationalUniversitiesModel->shopNum,
                            'boundary'      => [],
                            'grade'         => ProgrammingEnum::PC_GRADE_MAPPING[(int)$mapNationalUniversitiesModel->grade] ?? '',
                            'label'         => [],
                            'image'         => $auditCover,
                            'special'       => [],
                            'openPotential' => (float)optional($latestAudit)->openPotential,
                            'province'      => $mapNationalUniversitiesModel->province,
                            'city'          => $mapNationalUniversitiesModel->city,
                            'district'      => $mapNationalUniversitiesModel->district,
                            'address'       => $mapNationalUniversitiesModel->address,
                            'distance'      => $universitieWgNumbers[$mapNationalUniversitiesModel->wgNumber] ?? 99999,
                        ];

                        if ($collectionRes) {
                            $collectionList[] = $temp;
                        }

                        $data[] = $temp;
                    }
                });
        }
        if (in_array(ProgrammingEnum::PC_TYPE_LIST_HEAD_RESIDENCE, $typeArr) || !strlen($type)) {
            $residenceWgNumbers = [];
            foreach ($dotList as $dot) {
                // 过滤不是小区的
                if (substr($dot[0], 0, 4) != 'XQ99') {
                    continue;
                }
                $residenceWgNumbers[(int)substr($dot[0], 4)] = (int)$dot[1];
            }

            CityResidencePriceModel::query()
                ->whereIn('id', array_keys($residenceWgNumbers))
                ->with([
                    'resourceWithMapRel',
                ])
                ->chunk(100, function ($cityResidencePriceModels) use (&$data, $residenceWgNumbers, $collection, &$collectionList) {
                    foreach ($cityResidencePriceModels as $cityResidencePriceModel) {

                        $temp = [
                            'id'       => $cityResidencePriceModel->id,
                            'name'     => $cityResidencePriceModel->name,
                            'type'     => ProgrammingEnum::PC_TYPE_LIST_HEAD_RESIDENCE,
                            'wgNumber' => $cityResidencePriceModel->wgNumber,
                            'collection' => $collectionRes = in_array($cityResidencePriceModel->wgNumber, $collection),
                            'lat'      => $cityResidencePriceModel->centerLatitude,
                            'lng'      => $cityResidencePriceModel->centerLongitude,
                            'boundary' => [],
                            'grade'    => '',
                            'label'    => [],
                            'head'     => '',
                            'image'    => optional($cityResidencePriceModel->resourceWithMapRel)->url ? picturePath($cityResidencePriceModel->resourceWithMapRel->url) : SandTableEnum::DEFAULT_COVER_IMAGE_BASIC,
                            'special'  => [],
                            'province' => $cityResidencePriceModel->province,
                            'city'     => $cityResidencePriceModel->city,
                            'district' => $cityResidencePriceModel->district,
                            'address'  => $cityResidencePriceModel->name,
                            'distance' => $residenceWgNumbers[$cityResidencePriceModel->id] ?? 99999,
                        ];


                        if ($collectionRes) {
                            $collectionList[] = $temp;
                        }

                        $data[] = $temp;
                    }
                });

        }
        if (in_array(ProgrammingEnum::PC_TYPE_LIST_HEAD_PARK, $typeArr) || !strlen($type)) {
            $parkWgNumbers = [];
            foreach ($dotList as $dot) {
                // 过滤不是产业园的
                if (substr($dot[0], 0, 3) != 'CYY') {
                    continue;
                }
                $parkWgNumbers[$dot[0]] = (int)$dot[1];
            }

            MapNationalIndustrialParkModel::query()
                ->where('settle', ProgrammingEnum::SETTLE_STATUS_OFF)
                ->whereIn('wgNumber', array_keys($parkWgNumbers))
                ->with([
                    'resourceWithMapRel',
                    'logRel' => function ($q) {
                        $q->with(['resourceRelByCover']);
                    }
                ])
                ->chunk(100, function ($mapNationalIndustrialParkModels) use (&$data, $parkWgNumbers, $collection, &$collectionList) {
                    foreach ($mapNationalIndustrialParkModels as $mapNationalIndustrialParkModel) {
                        $auditCover = optional($mapNationalIndustrialParkModel->resourceWithMapRel)->url ? picturePath($mapNationalIndustrialParkModel->resourceWithMapRel->url) : SandTableEnum::DEFAULT_COVER_IMAGE_BASIC;
                        $latestAudit = null;
                        if (count($mapNationalIndustrialParkModel->logRel)) {
                            $latestAudit = collect($mapNationalIndustrialParkModel->logRel)->sortByDesc('updatedAt')->first();
                            if (count($latestAudit->resourceRelByCover)) {
                                foreach ($latestAudit->resourceRelByCover as $resourceRelByCover) {
                                    $auditCover = picturePath($resourceRelByCover->url);
                                    break;
                                }
                            }
                        }
                        $temp = [
                            'id'       => $mapNationalIndustrialParkModel->id,
                            'name'     => $mapNationalIndustrialParkModel->name,
                            'type'     => ProgrammingEnum::PC_TYPE_LIST_HEAD_PARK,
                            'wgNumber' => $mapNationalIndustrialParkModel->wgNumber,
                            'collection' => $collectionRes = in_array($mapNationalIndustrialParkModel->wgNumber, $collection),
                            'lat'      => $mapNationalIndustrialParkModel->lat,
                            'lng'      => $mapNationalIndustrialParkModel->lon,
                            'shopNum'  => $mapNationalIndustrialParkModel->shopNum,
                            'boundary' => [],
                            'grade'    => ProgrammingEnum::PC_GRADE_MAPPING[(int)$mapNationalIndustrialParkModel->grade] ?? '',
                            'label'    => [],
                            'image'    => $auditCover,
                            'special'  => [],
                            'province' => $mapNationalIndustrialParkModel->province,
                            'city'     => $mapNationalIndustrialParkModel->city,
                            'district' => $mapNationalIndustrialParkModel->district,
                            'address'  => $mapNationalIndustrialParkModel->name,
                            'distance' => $parkWgNumbers[$mapNationalIndustrialParkModel->wgNumber] ?? 99999
                        ];

                        if ($collectionRes) {
                            $collectionList[] = $temp;
                        }

                        $data[] = $temp;
                    }
                });
        }
        if (in_array(ProgrammingEnum::PC_TYPE_LIST_HEAD_COMPETITION, $typeArr) || !strlen($type)) {
            $competitionWgNumbers = [];
            foreach ($dotList as $dot) {
                // 过滤不是竞品的
                if (substr($dot[0], 0, 2) != 'PP') {
                    continue;
                }
                $competitionWgNumbers[$dot[0]] = (int)$dot[1];
            }

            MapNationalBrandShopModel::query()
                ->whereIn('wgNumber', array_keys($competitionWgNumbers))
                ->whereIn('brand', ProgrammingEnum::BRAND_SAND_TABLE_COMPETITIVE_PRODUCTS_MAPPING)
                ->with([
                    'resourceWithMapRel',
                ])
                ->chunk(100, function ($mapNationalBrandShopModels) use (&$data, $competitionWgNumbers) {
                    foreach ($mapNationalBrandShopModels as $mapNationalBrandShopModel) {

                        $special = [];
                        if ($mapNationalBrandShopModel->openingTime) {
                            $special[] = [
                                'name'  => '开业时间',
                                'value' => $mapNationalBrandShopModel->openingTime ?: '-',
                            ];
                        }

                        $data[] = [
                            'id'       => $mapNationalBrandShopModel->id,
                            'name'     => strpos($mapNationalBrandShopModel->name, $mapNationalBrandShopModel->brand) !== false ? $mapNationalBrandShopModel->name : $mapNationalBrandShopModel->brand . $mapNationalBrandShopModel->name,
                            'brand'    => $mapNationalBrandShopModel->brand,
                            'key'      => ProgrammingEnum::BRAND_SHOP_MAPPING[$mapNationalBrandShopModel->brand] ?? '',
                            'type'     => ProgrammingEnum::PC_TYPE_LIST_HEAD_COMPETITION,
                            'wgNumber' => $mapNationalBrandShopModel->wgNumber,
                            'collection' => false,
                            'lat'      => $mapNationalBrandShopModel->lat,
                            'lng'      => $mapNationalBrandShopModel->lon,
                            'boundary' => [],
                            'grade'    => '',
                            'label'    => [],
                            'head'     => '',
                            'image'    => (optional($mapNationalBrandShopModel->resourceWithMapRel)->url ? picturePath($mapNationalBrandShopModel->resourceWithMapRel->url) : '') ?: (ProgrammingEnum::BRAND_SHOP_LOG_IMAGE_MAPPING[$mapNationalBrandShopModel->brand] ?? SandTableEnum::DEFAULT_COVER_IMAGE_BASIC),
                            'special'  => $special,
                            'province' => $mapNationalBrandShopModel->province,
                            'city'     => $mapNationalBrandShopModel->city,
                            'district' => $mapNationalBrandShopModel->district,
                            'address'  => $mapNationalBrandShopModel->address,
                            'distance' => $competitionWgNumbers[$mapNationalBrandShopModel->wgNumber] ?? 99999,
                        ];
                    }
                });
        }
        if (in_array(ProgrammingEnum::PC_TYPE_LIST_HEAD_COMPLEMENT, $typeArr) || !strlen($type)) {
            $complementWgNumbers = [];
            foreach ($dotList as $dot) {
                // 过滤不是互补品的
                if (substr($dot[0], 0, 2) != 'PP') {
                    continue;
                }
                $complementWgNumbers[$dot[0]] = (int)$dot[1];
            }

            MapNationalBrandShopModel::query()
                ->whereIn('wgNumber', array_keys($complementWgNumbers))
                ->whereIn('brand', ProgrammingEnum::BRAND_SAND_TABLE_COMPLEMENTARY_PRODUCTS_MAPPING)
                ->with([
                    'resourceWithMapRel',
                ])
                ->chunk(100, function ($mapNationalBrandShopModels) use (&$data, $complementWgNumbers) {
                    foreach ($mapNationalBrandShopModels as $mapNationalBrandShopModel) {
                        $special = [];
                        if ($mapNationalBrandShopModel->openingTime) {
                            $special[] = [
                                'name'  => '开业时间',
                                'value' => $mapNationalBrandShopModel->openingTime ?: '-',
                            ];
                        }

                        $data[] = [
                            'id'       => $mapNationalBrandShopModel->id,
                            'name'     => strpos($mapNationalBrandShopModel->name, $mapNationalBrandShopModel->brand) !== false ? $mapNationalBrandShopModel->name : $mapNationalBrandShopModel->brand . $mapNationalBrandShopModel->name,
                            'brand'    => $mapNationalBrandShopModel->brand,
                            'key'      => ProgrammingEnum::BRAND_SHOP_MAPPING[$mapNationalBrandShopModel->brand] ?? '',
                            'type'     => ProgrammingEnum::PC_TYPE_LIST_HEAD_COMPLEMENT,
                            'wgNumber' => $mapNationalBrandShopModel->wgNumber,
                            'collection' => false,
                            'lat'      => $mapNationalBrandShopModel->lat,
                            'lng'      => $mapNationalBrandShopModel->lon,
                            'boundary' => [],
                            'grade'    => '',
                            'label'    => [],
                            'head'     => '',
                            'image'    => (optional($mapNationalBrandShopModel->resourceWithMapRel)->url ? picturePath($mapNationalBrandShopModel->resourceWithMapRel->url) : '') ?: (ProgrammingEnum::BRAND_SHOP_LOG_IMAGE_MAPPING[$mapNationalBrandShopModel->brand] ?? SandTableEnum::DEFAULT_COVER_IMAGE_BASIC),
                            'special'  => $special,
                            'province' => $mapNationalBrandShopModel->province,
                            'city'     => $mapNationalBrandShopModel->city,
                            'district' => $mapNationalBrandShopModel->district,
                            'address'  => $mapNationalBrandShopModel->address,
                            'distance' => $complementWgNumbers[$mapNationalBrandShopModel->wgNumber] ?? 99999,
                        ];
                    }
                });
        }

        $list = collect($data)->sortBy('distance')->values()->toArray();

        if (strlen($searchInput) && $cityCode) {
            $nearbyShop = [];
        } elseif (!empty($list)) {
            // 附近门店
            $nearbyShop             = GuanyuanDataService::closestShop($list[0]['lat'], $list[0]['lng'], '', false);
            $nearbyShop['distance'] = (int)($nearbyShop['distance'] * 1000);
        } else {
            $nearbyShop = [];
        }

        $userPowerAll  = [];
        $chooseManager = [];
        $recordList    = [];
        $showAddRecord = false;

        if ($id) {
            // 判断当前用户是否拥有指派开发经理的角色
            $province = self::getAssignPower($lat, $lng)['result']['address_component']['province'] ?? '';
            if (strlen($province)) {
                $organizationManageId = (int)OpenShopOrganizationRegionMappingModel::query()
                    ->where('provinceName', $province)
                    ->value('manageId');

                OpenShopOrganizationManageModel::query()
                    ->whereIn('id', [1, $organizationManageId])
                    ->get()
                    ->each(function (OpenShopOrganizationManageModel $openShopOrganizationManageModel) use (&$userPowerAll) {
                        $userPowerAll[] = $openShopOrganizationManageModel->operationUid;

                        $attachUser = json_decode($openShopOrganizationManageModel->operationAttacheUser, true);
                        foreach ($attachUser as $item) {
                            $userPowerAll[] = $item['uid'];
                        }
                    });
            }

            $intendedSiteLocationModel = IntendedSiteSelectionModel::query()
                ->where('id', $id)
                ->with(['records.resourcesIntendedSiteLocationRel'])
                ->first();


            if ($intendedSiteLocationModel != null && $intendedSiteLocationModel->followUpUserId) {
                $chooseManager = (new RmsUserApi())->getUserInfoByIds([$intendedSiteLocationModel->followUpUserId], ['id', 'username'])['data'][0] ?? [];
            }
            if ($intendedSiteLocationModel != null) {
                foreach ($intendedSiteLocationModel->records as $record) {
                    $files = $record->resourcesIntendedSiteLocationRel->map(function ($resource) {
                        return FileUtil::domain() . '/' . $resource->url;
                    })->toArray();

                    $recordList[] = [
                        'files'      => $files,
                        'status'     => $record->status,
                        'statusText' => IntendedSiteLocationEnum::INTENDED_SITE_LOCATION_MAPPING[$record->status] ?? '',
                        'username'   => $record->userName,
                        'createdAt'  => $record->createdAt->toDateTimeString(),
                        'cover'      => SandTableEnum::DEFAULT_KUAFU_LOGO,
                        'content'    => $record->logContent,
                        'id'         => $record->id,
                    ];
                }
            }

            if ($rmsUserId == $intendedSiteLocationModel->followUpUserId) {
                $showAddRecord = true;
            }
        }

        return [
            'shop'          => $nearbyShop,
            'list'          => $list,
            'collection'    => $collectionList,
            'showAssign'    => in_array($rmsUserId, $userPowerAll),
            'showAddRecord' => $showAddRecord,
            'chooseManager' => $chooseManager,
            'recordList'    => $recordList,
        ];
    }


    public static function searchDots($text, $cityCode): array
    {
        return (new WangguiSearchDotModel)->search($text, $cityCode);
    }

    public static function collection(int $collection, string $wgNumber, string $type, $rmsUserId)
    {
        switch ($collection) {
            case WangguiCollectionDotModel::COLLECTION_ON:
                // 添加
                $collectionModel = WangguiCollectionDotModel::query()
                    ->firstOrNew([
                        'type'         => $type,
                        'wgNumber'     => $wgNumber,
                        'createdByUid' => $rmsUserId,
                    ]);
                $collectionModel->save();

                break;
            case WangguiCollectionDotModel::COLLECTION_OFF:
                // 删除
                WangguiCollectionDotModel::query()
                    ->where('type', $type)
                    ->where('wgNumber', $wgNumber)
                    ->where('createdByUid', $rmsUserId)
                    ->delete();
                break;
            default:
        }
    }

    /*
     * 根据type和网规编号获得详情
     */
    public static function getDotDetailByTypeAndWgNumber($type, $wgNumber, $selectParams = ['*']): array
    {
        switch ($type) {
            case ProgrammingEnum::PC_TYPE_LIST_HEAD_MALL:
                $model = SiteLocationMallModel::query()
                    ->where('wgNumber', $wgNumber)
                    ->select($selectParams)
                    ->first();
                break;
            case ProgrammingEnum::PC_TYPE_LIST_HEAD_STREET:
                $model = MapNationalStreetModel::query()
                    ->where('wgNumber', $wgNumber)
                    ->select($selectParams)
                    ->first();
                break;
            case ProgrammingEnum::PC_TYPE_LIST_HEAD_COMMUNITY:
                $model = MapNationalCommunityModel::query()
                    ->where('wgNumber', $wgNumber)
                    ->select($selectParams)
                    ->first();
                break;
            case ProgrammingEnum::PC_TYPE_LIST_HEAD_UNIVERSITIES:
                $model = MapNationalUniversitiesModel::query()
                    ->where('wgNumber', $wgNumber)
                    ->select($selectParams)
                    ->first();
                break;
            default:
                self::throwErr('网规类型错误');
        }
        return [
            'lat'          => $model->lat,
            'lng'          => $model->lng,
            'name'         => $model->nameText,
            'address'      => $model->address,
            'province'     => $model->province,
            'city'         => $model->city,
            'district'     => $model->district,
            'provinceCode' => $model->provinceCode,
            'cityCode'     => $model->cityCode,
            'districtCode' => $model->districtCode,
        ];
    }


    public static function getAssignPower($lat, $lng)
    {
        try {
            $res = Http::withHeaders(['Content-Type' => 'application/json; charset=utf-8'])
                ->get(sprintf(config('area.getAreaUrl'), $lat, $lng))
                ->json();

            if (isset($res['status']) && $res['status'] == 0) {
                return $res;
            } else {
                return [];
            }
        } catch (\Exception $exception) {
            return [];
        }
    }

    public static function assignManager($id, int $managerId, $rmsUserName)
    {
        $intendedSiteLocationModel = IntendedSiteSelectionModel::query()
            ->with([
                "shopRel" => function ($query) {
                    $query->with([
                        "signOrderRel" => function ($query) {
                            $query->with([
                                "developmentConsultantRel",
                                "progressRel",
                                "startBusinessRel",
                                "contractRel"
                            ]);
                        }
                    ]);
                }
            ])
            ->where("id", $id)
            ->first();

        if ($intendedSiteLocationModel == null) {
            self::throwErr('意向址不存在', 404);
        }

        if ($intendedSiteLocationModel->followUpUserId == $managerId) {
            self::throwErr('重复的开发经理', 403);
        }

        if ($intendedSiteLocationModel->followUpUserId == 0) {
            $intendedSiteLocationModel->status = IntendedSiteLocationEnum::INTENDED_SITE_LOCATION_WAIT_FOLLOW_UP;
        }

        $intendedSiteLocationModel->followUpUserId = $managerId;
        $intendedSiteLocationModel->save();

        try {
            $rmsUserResponse = RmsUserRemote::getRmsUserByIds([$intendedSiteLocationModel->createdByUid]);
            $rmsUserInfo = $rmsUserResponse[0] ?? [];
            // 给开发经理发送消息
            FeishuMsgSupport::getInstance('意向址开发指派，请查收',
                array_merge([$managerId]))
                ->setContent(
                    ["name" => "意向区域", "value" => $intendedSiteLocationModel->addressPrefix],
                    ["name" => "门店编号", "value" => optional($intendedSiteLocationModel->shopRel)->shopCode],
                    ["name" => "指派人", "value" => $rmsUserName],
                    ["name" => '客户姓名', "value" => attributeGet($rmsUserInfo, "username", "")],
                    ["name" => '客户电话', "value" => attributeGet($rmsUserInfo, "mobile", "")],
                    ["name" => '提交时间', "value" => $intendedSiteLocationModel->createdAt->toDateTimeString()],
                )
                ->msgSend(["path" => "pages/self-contained/index?id={$intendedSiteLocationModel->id}&lat={$intendedSiteLocationModel->latitude}&lng={$intendedSiteLocationModel->longitude}&shopId=-1"]);
        } catch (\Exception $exception) {

        }
    }

    /**
     * @throws \Exception
     */
    public static function submitRecord($id, int $status, array $files, string $record, $rmsUserId, $rmsUsername)
    {
        $intendedModel = IntendedSiteSelectionModel::query()
            ->where('id', $id)
            ->first();

        if ($intendedModel == null) {
            self::throwErr('意向记录不存在');
        }

        if ($intendedModel->followUpUserId != $rmsUserId) {
            self::throwErr('您不能添加跟进记录，请联系省总指派');
        }

        $intendedModel->status = $status;
        $intendedModel->save();

        // 添加记录
        $model = OperateLogModel::add(
            OperateLogModel::BUSINESS_INTENDED_SITE_LOCATION,
            $id,
            $id,
            '',
            $record,
            $status,
            $rmsUserId,
            $rmsUsername,
        );

        // 添加图片
        ResourcesModel::moduleBusinessSingleResourcesUpdate(
            ResourcesModel::MODULE_TYPE_INTENDED_SITE_LOCATION,
            ResourcesModel::BUSINESS_INTENDED_SITE_LOCATION,
            'record',
            $model->id,
            $files,
        );

        // todo 消息推送
        event(new InsertEvent($id, $status, $record));
    }

    public static function recordList(int $cityType, int $cityCode, string $type, string $status, string $managerId, string $searchInput, int $pageNum, int $pageSize, $rmsUserId): array
    {
        // 权限控制-获取用户信息 省总-城市经理-开发
        $powerValue = [];
        OpenShopOrganizationManageModel::query()
            ->where('type', OpenShopOrganizationManageModel::HEADQUARTERS_ID)
            ->select(['operationUid', 'operationAttacheUser'])
            ->get()
            ->each(function (OpenShopOrganizationManageModel $openShopOrganizationManageModel) use (&$powerAll) {
                $powerAll[] = $openShopOrganizationManageModel->operationUid;
                foreach (json_decode($openShopOrganizationManageModel->operationAttacheUser, true) as $item) {
                    $powerAll[] = attributeGet($item, 'uid', 0);
                }
            });

        if (in_array($rmsUserId, $powerAll)) {
            $power = 'all';
        } else {
            $powerProvince = [];
            $powerCity     = [];
            OpenShopOrganizationManageModel::query()
                ->where('type', 2)
                ->select(['id', 'operationUid', 'operationAttacheUser'])
                ->with(['regionRel', 'managerUserRel'])
                ->get()
                ->each(function (OpenShopOrganizationManageModel $openShopOrganizationManageModel) use (&$powerCity, &$powerProvince) {
                    $provinceUserIds[] = $openShopOrganizationManageModel->operationUid;
                    foreach (json_decode($openShopOrganizationManageModel->operationAttacheUser, true) as $item) {
                        $provinceUserIds[] = attributeGet($item, 'uid', 0);
                    }

                    $provinceCodes = [];
                    if ($openShopOrganizationManageModel->regionRel->count()) {
                        foreach ($openShopOrganizationManageModel->regionRel as $province) {
                            $provinceCodes[] = attributeGet($province, 'provinceCode', 0);
                        }
                    }

                    foreach ($provinceUserIds as $provinceUserId) {
                        if (isset($powerProvince[$provinceUserId])) {
                            $powerProvince[$provinceUserId] = array_merge($powerProvince[$provinceUserId], $provinceCodes);
                        } else {
                            $powerProvince[$provinceUserId] = $provinceCodes;
                        }
                    }

                    if ($openShopOrganizationManageModel->managerUserRel->count()) {
                        foreach ($openShopOrganizationManageModel->managerUserRel as $item) {
                            if ($item->type != OpenShopOrganizationManageUserModel::TYPE_CITY_MANAGER) {
                                continue;
                            }
                            $powerCity[$item['userId']] = collect(json_decode($item->addressCodes, true))->map(function ($address) {
                                $prefix = explode('-', $address);
                                return $prefix[1] ?? 0;
                            })->unique()->values()->toArray();
                        }
                    }
                });
            if (in_array($rmsUserId, array_keys($powerProvince))) {
                $power      = 'province';
                $powerValue = $powerProvince[$rmsUserId];
            } elseif (in_array($rmsUserId, array_keys($powerCity))) {
                $power      = 'city';
                $powerValue = $powerCity[$rmsUserId];
            } else {
                $power = 'self';
            }
        }

        if ($power == 'self') {
            $developmentUserIds = collect(SiteLocationService::managerList()['managerLists'])->pluck('id')->toArray();
            if (!in_array($rmsUserId, $developmentUserIds)) {
                self::throwErr('暂无查看权限');
            }
        }

        $shopIds = [];
        // 根据searchInput 获得shopId
        if (strlen($searchInput)) {
            if (is_numeric($searchInput)) {
                // 手机号 门店编号
                if (strlen($searchInput) > 4) {
                    // 手机号
                    $orderNo = OpenShopUserBaseInfoModel::query()
                        ->where('mobile', $searchInput)
                        ->pluck('orderNo')
                        ->toArray();

                    $shopIds = OpenShopMainProcessModel::query()
                        ->whereIn('orderNo', $orderNo)
                        ->pluck('shopId')
                        ->toArray();

                } else {
                    // 门店编号
                    $shopIds = ShopModel::query()
                        ->where('shopCode', $searchInput)
                        ->pluck('id')
                        ->toArray();
                }
            } else {
                // 姓名
                $orderNos = OpenShopUserIdentityCardModel::query()
                    ->where('name', $searchInput)
                    ->pluck('orderNo')
                    ->toArray();

                $shopIds = OpenShopMainProcessModel::query()
                    ->whereIn('orderNo', $orderNos)
                    ->pluck('shopId')
                    ->toArray();
            }
        }

        $paginator = IntendedSiteSelectionModel::query()
            ->when(strlen($searchInput), function ($q) use ($shopIds) {
                $q->whereIn('shopId', $shopIds);
            })
            ->where(function ($q) use ($power, $powerValue, $rmsUserId) {
                switch ($power) {
                    case 'all':
                        break;
                    case 'province':
                        $q->whereIn('provinceCode', $powerValue)->orWhere('followUpUserId', $rmsUserId);
                        break;
                    case 'city':
                        $q->whereIn('cityCode', $powerValue)->orWhere('followUpUserId', $rmsUserId);
                        break;
                    default:
                        $q->where('followUpUserId', $rmsUserId);
                }
            })
            ->when($cityType, function ($q) use ($cityType, $cityCode){
                switch ($cityType) {
                    case 1:
                        $q->whereIn('province', OpenShopOrganizationRegionMappingModel::query()->where('manageId', $cityCode)->pluck('provinceCode')->toArray());
                        break;
                    case 2:
                        $q->where('provinceCode', $cityCode);
                        break;
                    case 3:
                        $q->where('cityCode', $cityCode);
                        break;
                }
            })
            ->when(strlen($type), function ($q) use ($type){
                $q->whereIn('type', explode(',', $type));
            })
            ->when(strlen($status), function ($q) use ($status){
                $q->whereIn('status', explode(',', $status));
            })
            ->when(strlen($managerId), function ($q) use ($managerId){
                $q->whereIn('followUpUserId', explode(',', $managerId));
            })
            ->orderByDesc('id')
            ->with(['shopRel', 'records'])
            ->paginate($pageSize, ['*'], 'pageNum', $pageNum);

        $userData = (new RmsUserApi())->getUserInfoByIds(array_merge($paginator->pluck('createdByUid')->toArray(), $paginator->pluck('followUpUserId')->toArray()), ['id', 'username'])['data'] ?? [];
        $userList = array_column($userData, 'username', 'id');

        $list = $paginator->map(function (IntendedSiteSelectionModel $intendedSiteSelectionModel) use ($userList) {

            $lastManagerName  = $userList[$intendedSiteSelectionModel->followUpUserId] ?? '';
            $lastFollowUpDate = '-';
            foreach ($intendedSiteSelectionModel->records as $record) {
                $lastManagerName  = $record->userName;
                $lastFollowUpDate = $record->createdAt->toDateTimeString();
            }

            return [
                "id"               => $intendedSiteSelectionModel->id,
                "type"             => $intendedSiteSelectionModel->type,
                "status"           => $intendedSiteSelectionModel->status,
                "shopId"           => -1,
                "statusText"       => IntendedSiteLocationEnum::INTENDED_SITE_LOCATION_MAPPING[$intendedSiteSelectionModel->status] ?? '',
                "shopCode"         => optional($intendedSiteSelectionModel->shopRel)->shopCode ?: '',
                "username"         => $userList[$intendedSiteSelectionModel->createdByUid] ?? '-',
                "managerUsername"  => $lastManagerName,
                "followUpDateTime" => $lastFollowUpDate,
                "lat"              => $intendedSiteSelectionModel->latitude,
                "lng"              => $intendedSiteSelectionModel->longitude,
                "poiName"          => $intendedSiteSelectionModel->poiName,
                "poiAddress"       => $intendedSiteSelectionModel->poiAddress,
                "siteSelectionImg" => $intendedSiteSelectionModel->siteSelectionImg,
                "createdAtText"    => $intendedSiteSelectionModel->createdAt->format("Y-m-d H:i:s")
            ];
        });

        return [
            'list'           => $list,
            'count'          => $paginator->total(),
            'pageNum'        => $pageNum,
            'pageSize'       => $pageSize,
        ];
    }

    /**
     * 获得分公司列表
     * @return array
     * @throws GuzzleException
     */
    public static function subCompany(): array
    {
        $areaList = collect(RmsAreaRemote::getAreaListAll()['areaList'] ?? []);
        return OpenShopOrganizationManageModel::query()
            ->with(['regionRel'])
            ->get()
            ->map(function ($item) use ($areaList) {
                $children = [];
                if ($item->regionRel != null) {
                    foreach ($item->regionRel as $val) {
                        $children[] = [
                            'label'    => $val->provinceName,
                            'type'     => OpenShopOrganizationManageModel::TYPE_PROVINCE,
                            'value'    => $val->provinceCode,
                            'children' => $areaList
                                ->where('areaPid', $val->provinceCode)
                                ->map(function ($area) use ($areaList) {
                                    return [
                                        'label' => $area['cnShortName'],
                                        'value' => $area['areaId'],
                                        'type'  => OpenShopOrganizationManageModel::TYPE_CITY,
                                    ];
                                },
                                )->values()->filter()->toArray(),
                        ];
                    }
                }
                return [
                    'label'    => $item->name,
                    'value'    => $item->id,
                    'children' => $children,
                ];
            },
            )->toArray();
    }

}
